package com.bookstore.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bookstore.entity.dto.TrolleyDTO;
import com.bookstore.entity.po.TrolleyPO;
import com.bookstore.entity.pojo.R;
import com.bookstore.entity.vo.TrolleyVO;
import com.bookstore.service.TrolleyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("trolley")
public class TrolleyController {
    @Autowired
    TrolleyService trolleyService;

    @GetMapping()
    public R getTrolleyByUserName (String userName) {
        List<TrolleyVO> byUserName = trolleyService.getByUserName(userName);
        return R.success(byUserName);
    }

    @PostMapping
    public R save (@RequestBody TrolleyPO trolleyPO) {
        System.out.println(trolleyPO);
        TrolleyPO one = trolleyService.getOne(new QueryWrapper<TrolleyPO>().eq("book_id", trolleyPO.getBookId()).and(q -> q.eq("user_name", trolleyPO.getUserName())));
        if (one != null) {
            return R.success();
        }
        trolleyPO.setCreateTime(new Date());
        trolleyPO.setChangeTime(new Date());
        trolleyPO.setNum(trolleyPO.getNum());
        boolean save = trolleyService.save(trolleyPO);
        return save?R.success():R.error();
    }

    @DeleteMapping
    public R del (@RequestBody TrolleyDTO trolleyDTO) {

        boolean remove = trolleyService.remove(new QueryWrapper<TrolleyPO>().eq("book_id", trolleyDTO.getBookId()).eq("user_name", trolleyDTO.getUserName()));
        return remove?R.success():R.error();
    }
}
